<template>
  <iframe v-if="src" ref="iframeRef" :src="src"></iframe>
</template>

<script setup lang="ts">
import { defineEmits, defineProps, onBeforeUnmount, onMounted, ref } from 'vue'

interface Props {
  src: string
}

const props = withDefaults(defineProps<Props>(), {})

const emit = defineEmits<{
  (e: 'on-load'): void
  (e: 'on-message', value: any): void
}>()

const iframeRef = ref<HTMLIFrameElement | null>(null)

const handleLoad = () => {
  emit('on-load')
}

const handleMessage = ({ data, source }: { data: any, source: Window }) => {
  if (iframeRef.value && source === iframeRef.value.contentWindow) {
    data = JSON.parse(data)
    if (data.source === 'fileView' && data.action === 'picture') {
      // store.dispatch("previewImage", { index: data.params.index, list: data.params.array });
    }
    emit('on-message', data)
  }
}

const postMessage = (message: any, targetOrigin = '*') => {
  if (iframeRef.value) {
    iframeRef.value.contentWindow?.postMessage(message, targetOrigin)
  }
}

onMounted(() => {
  if (iframeRef.value) {
    iframeRef.value.addEventListener('load', handleLoad)
  }
  window.addEventListener('message', handleMessage)
})

onBeforeUnmount(() => {
  if (iframeRef.value) {
    iframeRef.value.removeEventListener('load', handleLoad)
  }
  window.removeEventListener('message', handleMessage)
})
</script>
